package router

import (
	"broker/interface/iserver"
	"broker/struct/datapack"
	"broker/struct/model"
	"broker/utils"

	"broker/utils/logger"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/4/25 10:47 下午
 **/

type PublishRouter struct {
	BaseRouter
}

func NewPublishRouter() *PublishRouter {
	return &PublishRouter{}
}

func (pr *PublishRouter) PreHandle(request iserver.IRequest) interface{} {
	pubMsg := model.NewPublishMessage()
	//解包保留位
	reserved := request.GetReserved()
	pubMsg.DUP = utils.GetBinaryBit(reserved, 4)
	pubMsg.Qos = (utils.GetBinaryBit(reserved, 5) << 1) | utils.GetBinaryBit(reserved, 6)
	pubMsg.Retain = utils.GetBinaryBit(reserved, 7)
	//解包发布数据
	msgData := request.GetData()

	pdp := datapack.NewPublishDataPack(pubMsg)
	tempMsg, err := pdp.UnPack(msgData)
	if err != nil {
		logger.Error.Println("[Publish] publish datapack error", err)
		return nil
	}
	pubMsg = tempMsg.(*model.PublishMessage)
	return pubMsg
}

func (pr *PublishRouter) Handle(request iserver.IRequest, param interface{}) interface{} {
	pubMsg := param.(*model.PublishMessage)
	pubMsg.DUP = 0
	pubMsg.Qos = 0
	//封包保留位
	var reserved byte = 0
	reserved |= pubMsg.DUP << 3
	reserved |= pubMsg.Qos << 1
	reserved |= pubMsg.Retain
	pubMsg.SetReserved(reserved)
	pdp := datapack.NewPublishDataPack(nil)
	msgData, err := pdp.Pack(pubMsg)
	if err != nil {
		logger.Error.Println("[Publish] pack publish data err", err)
	}
	pubMsg.SetData(msgData)
	go request.GetConnection().GetTcpServer().GetTopicManager().Publish(*pubMsg, request.GetConnection())
	return pubMsg
}
func (pr *PublishRouter) PostHandle(request iserver.IRequest, param interface{}) {
	pubMsg := param.(*model.PublishMessage)
	if pubMsg.Qos > 0 {
		logger.Info.Println("[Publish] send puback")
	}
}
